package com.oocl.homework.verify;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.oocl.homework.exception.VerifyException;

public class MyVerify implements Verifyable{

	
	public Object verify(Object object) throws VerifyException {
		 Field[] fields = object.getClass().getDeclaredFields();
	        for(Field field :fields){
	            if(field.isAnnotationPresent(Verify.class)){
	                Verify verify = (Verify) field.getAnnotation(Verify.class);
	                String patternString = verify.pattern();
	                if(!patternString.equals("")){
	                	Pattern pattern = Pattern.compile(patternString);
								try {
									field.setAccessible(true);
									if (field.get(object)==null) {
										continue;
									}
									Matcher matcher = pattern.matcher(field.get(object).toString());
				                	int count =0;
				                	while (matcher.find()) {
										count++;
									}
				                	if(count>1||count==0){
									  
									field.set(object, null);
									}
								} catch (IllegalArgumentException e) {
									throw new VerifyException(field.getName()+" Assignment failure,IllegalArgument", e);
								} catch (IllegalAccessException e) {
									throw new VerifyException(field.getName()+" Assignment failure,IllegalAccess", e);
								}
	                	}
	                }
	                
	        }
		
		return object;
		
	}
	

}
